import akka.actor.Actor.Receive
import akka.actor.{Actor, ActorRef, ActorSystem, Props}

/**
  * Created by kylin on 17-2-14.
  */

case object PingMsg

case object PongMSg

case object StartMsg

case object StopMsg


class PingAct(pong: ActorRef) extends Actor {
  var count = 0

  def pr() {
    count += 1;
    println("ping")
  }

  override def receive = {
    case StartMsg =>
      pr()
      pong ! PingMsg
    case PongMSg =>
      pr()
      if (count > 20) {
        sender() ! StopMsg
        println("ping stopped")
        context.stop(self)
      } else {
        sender() ! PingMsg
      }
    case _ => println("ping something else")
  }
}

class PongAct extends Actor {
  override def receive = {
    case PingMsg =>
      println("pong")
      sender() ! PongMSg
    case StopMsg =>
      println("pong stopped")
      context.stop(self)
    case _ => println("something else ")
  }

  override def postStop(): Unit = {
    super.postStop()
  }
}

object concurrent {

  def main(args: Array[String]): Unit = {
    val s = ActorSystem("pp")

//    val pong = s.actorOf(Props[PongAct])
//    val ping = s.actorOf(Props(new PingAct(pong)))
//    ping ! StartMsg

    val a=s.actorOf(Props[HelloAct])

    for(i <- 0 to 10)
      {
        println("msg")
        a ! PingMsg
        println("done msg")
      }

    a ! StopMsg

    s.registerOnTermination(println("main done"))
  }

//  case object M

  class HelloAct extends Actor {
    override def receive = {
      case PingMsg =>
        Thread.sleep(300)
        println("hello")

      case StopMsg=>
        println("shutdown recv")
        context.stop(self)

      case _=> println("unknown msg")
    }

    override def postStop(): Unit = {
      context.system.terminate()
    }
  }

}
